const path = require("path");
const router = require("./router");
class Front{
	constructor(req, res, conf){
		this.route = router.init(req, conf);
		this.config = conf;
		this.dispatch(req, res);
	}
	dispatch(req, res){
		let router = this.route.router;
		let control_file = "";
		let action = "";
		
		switch (router.module){
			case "common":
				control_file += "../controller/common.js";
				action = router.controll;
			break;
			case "public":
			break;
			case "error":
			break;
			default:
				control_file += path.relative(__dirname,this.config.dir.get("root"));
				control_file += "/"+this.config.dir.get("app")+"/"+this.config.dir.get("appname");
				control_file += "/"+this.config.dir.get("controll")+"/"+router.module+"/";
				control_file += router.controll+".js";
				control_file = path.normalize(control_file);
				action = router["action"];
				this.config.router.route = router; 
			break;
		}
		try{
			let controll = require(control_file);
			let ctr = new controll(req, res, this.config);
				ctr[action](router["action"]);
		} catch(err) {
			res.statusCode = 404;
			res.setHeader("Content-Type", "text/html");
			res.write("<h1>404 Not found!</h1><p>Prowed by K-NodeJs-Framework</p>", "utf8");
			res.end();
			console.log(err.message);
		}
	}
}

exports.dispatch = function(req, res, conf){
	let front = new Front(req, res, conf);
	return front;
}